<template>
  <el-aside>
    <img class="logo" src="@/assets/images/logo.svg" alt="" />

    <el-scrollbar>
      <el-menu
        :default-active="activeIndex"
        class="el-menu-vertical-demo"
        :collapse="isCollapse"
        :default-openeds="defaultOpeneds"
        @open="handleOpen"
        @close="handleClose"
        @select="handleSelect"
      >
        <template v-for="item in menuRoutes" :key="item.path">
          <!-- 有子菜单的情况 -->
          <el-sub-menu
            v-if="item.children && item.children.length > 0"
            :index="item.path"
            :class="{ 'is-active-parent': isParentActive(item.path) }"
          >
            <template #title>
              <el-icon v-if="item?.meta?.icon">
                <component :is="getIconComponent(item?.meta?.icon)" />
              </el-icon>
              <span>{{ item?.meta?.title }}</span>
            </template>

            <!-- 递归渲染子菜单 -->
            <template v-for="child in item.children" :key="child.path">
              <!-- 子菜单还有子菜单 -->
              <el-sub-menu
                v-if="child.children && child.children.length > 0"
                :index="child.path"
                :class="{ 'is-active-parent': isParentActive(child.path) }"
              >
                <template #title>
                  <span>{{ child?.meta?.title }}</span>
                </template>

                <el-menu-item
                  v-for="grandChild in child.children"
                  :key="grandChild.path"
                  :index="grandChild.path"
                >
                  <template #title>{{ grandChild?.meta?.title }}</template>
                </el-menu-item>
              </el-sub-menu>

              <!-- 普通子菜单项 -->
              <el-menu-item v-else :index="child.path">
                <template #title>{{ child?.meta?.title }}</template>
              </el-menu-item>
            </template>
          </el-sub-menu>

          <!-- 没有子菜单的情况 -->
          <el-menu-item v-else :index="item.path">
            <el-icon v-if="item.meta?.icon">
              <component :is="getIconComponent(item?.meta?.icon)" />
            </el-icon>
            <template #title>{{ item?.meta?.title }}</template>
          </el-menu-item>
        </template>
      </el-menu>
    </el-scrollbar>

    <div class="aside-expandFold" @click="isCollapse = !isCollapse">
      <el-icon v-if="!isCollapse" class="rotate-icon"><DArrowLeft /></el-icon>
      <el-icon v-else><DArrowRight /></el-icon>
    </div>
  </el-aside>
</template>

<script setup lang="ts" name="Aside">
import { ref, computed } from "vue";
import {
  Setting,
  DArrowLeft,
  DArrowRight,
  House,
  Search,
  User,
  UserFilled,
  ShoppingCart,
  List,
  Goods,
  Grid,
} from "@element-plus/icons-vue";
import { routes } from "@/router/routes.js";
import { useRouter } from "vue-router";

const router = useRouter();

// 获取布局路由的子路由作为菜单数据
const menuRoutes = computed(() => {
  const layoutRoute = routes.find(route => route.name === 'layout');
  return layoutRoute?.children?.filter(child => child.path !== '/') || [];
});

const iconMap = {
  House,
  Search,
  Setting,
  User,
  UserFilled,
  ShoppingCart,
  List,
  Goods,
  Grid,
};

const getIconComponent = (iconName: keyof typeof iconMap) => {
  return iconMap[iconName];
};

const activeIndex = ref("/home"); // 设置为实际的路由路径
const isCollapse = ref(false);

// 计算需要默认展开的菜单
const defaultOpeneds = computed(() => {
  const openeds: string[] = [];
  const currentPath = activeIndex.value;

  // 遍历所有路由，找到当前路径的父级路由
  const findParentRoutes = (routeList: any[], targetPath: string) => {
    for (const route of routeList) {
      if (route.children && route.children.length > 0) {
        // 检查是否是直接父级
        const isDirectParent = route.children.some(
          (child: any) =>
            child.path === targetPath ||
            (child.children &&
              child.children.some(
                (grandChild: any) => grandChild.path === targetPath
              ))
        );

        if (isDirectParent) {
          openeds.push(route.path);

          // 检查二级菜单
          for (const child of route.children) {
            if (
              child.children &&
              child.children.some(
                (grandChild: any) => grandChild.path === targetPath
              )
            ) {
              openeds.push(child.path);
            }
          }
        }
      }
    }
  };

  findParentRoutes(menuRoutes.value, currentPath);
  return openeds;
});

// 判断父级菜单是否应该显示选中状态
const isParentActive = (parentPath: string) => {
  const currentPath = activeIndex.value;

  // 查找该父级路径下是否包含当前选中的路径
  const findInChildren = (
    routeList: any[],
    parentPath: string,
    targetPath: string
  ): boolean => {
    const parentRoute = routeList.find((route) => route.path === parentPath);
    if (!parentRoute || !parentRoute.children) return false;

    return parentRoute.children.some((child: any) => {
      if (child.path === targetPath) return true;
      if (child.children) {
        return child.children.some(
          (grandChild: any) => grandChild.path === targetPath
        );
      }
      return false;
    });
  };

  return findInChildren(menuRoutes.value, parentPath, currentPath);
};

const handleSelect = (index: string) => {
  activeIndex.value = index;
  console.log("Selected menu:", index);
  router.push(index);
};

const handleOpen = (key: string, keyPath: string[]) => {
  console.log("Menu opened:", key, keyPath);
};

const handleClose = (key: string, keyPath: string[]) => {
  console.log("Menu closed:", key, keyPath);
};
</script>

<style scoped>
.el-aside {
  max-width: 200px;
  height: 100%;
  background: #edf0f4 !important;
  width: auto;

  .logo {
    display: block;
    width: 100%;
    height: 48px;
    padding: 0;
    margin: 0;
    line-height: 48px;
  }

  .el-menu {
    height: calc(100% - 96px);
    border: 0;
    background: #edf0f4 !important;
  }

  .aside-expandFold {
    height: 48px;
    font-size: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bolder;
    cursor: pointer;
  }
}

.rotate-icon {
  transition: transform 0.3s ease;
}

/* 自定义父级菜单选中状态样式 */
:deep(.el-sub-menu.is-active-parent) {
  & > .el-sub-menu__title {
    color: var(--el-menu-active-color) !important;
    background-color: var(--el-menu-hover-bg-color) !important;

    .el-icon {
      color: var(--el-menu-active-color) !important;
    }
  }
}

/* 折叠状态下的父级菜单选中样式 */
:deep(.el-menu--collapse .el-sub-menu.is-active-parent > .el-sub-menu__title) {
  background-color: var(--el-menu-active-color) !important;

  .el-icon {
    color: #fff !important;
  }
}

:deep(.el-scrollbar) {
  height: calc(100vh - 96px);
}
</style>
